package com.idopartx.phonelightning.ui.home.calllightning

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import com.dotools.umlibrary.UMPostUtils
import com.idopartx.phonelightning.R
import com.idopartx.phonelightning.common.Constant
import com.idopartx.phonelightning.databinding.ActivityCallLightningBinding
import com.idopartx.phonelightning.databinding.FooterCallLightningBinding
import com.idopartx.phonelightning.databinding.HeaderCallLightningBinding
import com.idopartx.phonelightning.entity.CallLightningCache
import com.idopartx.phonelightning.entity.CallLightningEntity
import com.idopartx.phonelightning.thread.LightningThread
import com.idopartx.phonelightning.ui.adapter.CallLightningAdapter
import com.idopartx.phonelightning.ui.base.BaseActivity
import com.idopartx.phonelightning.viewmodel.CallLightingViewModel
import com.tencent.mmkv.MMKV
import com.wuhenzhizao.titlebar.widget.CommonTitleBar

class CallLightningActivity : BaseActivity<ActivityCallLightningBinding>() {


    override fun initLayoutResId() = R.layout.activity_call_lightning

    private var thread: LightningThread? = null

    private val headerBinding: HeaderCallLightningBinding by lazy {
        DataBindingUtil.inflate(
            LayoutInflater.from(this),
            R.layout.header_call_lightning,
            binding.rvRoot,
            false
        )
    }

    private val footerBinding: FooterCallLightningBinding by lazy {
        DataBindingUtil.inflate(
            LayoutInflater.from(this),
            R.layout.footer_call_lightning,
            binding.rvRoot,
            false
        )
    }

    private val mAdapter: CallLightningAdapter by lazy {
        CallLightningAdapter(
            onItemClick = {
                Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show()
                MMKV.defaultMMKV().encode(Constant.SAVE_CURRENT_LIGHTNING, it)
                thread = null
                thread?.stopThread()
                thread = LightningThread(
                    applicationContext,
                    it.lightNightList,
                    if (it.isMorse == true) 1 else 4
                )
                thread?.start()

                MMKV.defaultMMKV()
                    .encode(
                        Constant.MMKV_SAVE_CALL_LIGHTNING,
                        CallLightningCache(mAdapter.data as ArrayList<CallLightningEntity>)
                    )


                viewModel.presetListLiveData.value?.forEach {
                    it.isCheck = false
                }
                MMKV.defaultMMKV()
                    .encode(
                        Constant.MMKV_SAVE_PRESET_CALL_LIGHTNING,
                        CallLightningCache(viewModel.presetListLiveData.value)
                    )

                footerBinding.llFooterList.removeAllViews()
                initFooterData(footerBinding)

            },
            onEditClick = { entity, position ->
                val intent = if (entity.isMorse == true) {
                    Intent(this, EditMorseActivity::class.java)
                } else {
                    Intent(this, EditCommonLightningActivity::class.java)
                }
                intent.putExtra(Constant.INTENT_POSITION, position)
                intent.putExtra(Constant.INTENT_LIGHTNING_VO, entity)
                startActivity(intent)
            },
            onDelClick = { _, position ->
                val callLightningCache = MMKV.defaultMMKV().decodeParcelable(
                    Constant.MMKV_SAVE_CALL_LIGHTNING,
                    CallLightningCache::class.java
                )

                callLightningCache?.callLightningList?.removeAt(position)
                MMKV.defaultMMKV().encode(Constant.MMKV_SAVE_CALL_LIGHTNING, callLightningCache)
                mAdapter.setList(callLightningCache?.callLightningList)

                if (mAdapter.data.isNullOrEmpty()) {
                    mAdapter.setEditStatus(false)
                    binding.viewTitleBar.rightTextView.text = "编辑"
                }

                setEditStatus()
            })
    }


    private val viewModel: CallLightingViewModel by lazy {
        ViewModelProvider(this)[CallLightingViewModel::class.java]
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        viewModel.getCommonList()
        viewModel.getPresetList()
        initAdapter()

        binding.viewTitleBar.setListener { v, action, _ ->
            when (action) {
                CommonTitleBar.ACTION_RIGHT_TEXT -> {
                    if (v is TextView) {
                        v.text = if (v.text.toString() == "编辑") {
                            viewModel.editStatusLiveData.value = true
                            "完成"
                        } else {
                            viewModel.editStatusLiveData.value = false
                            "编辑"
                        }
                        mAdapter.setEditStatus(viewModel.editStatusLiveData.value)
                    }
                }

                CommonTitleBar.ACTION_LEFT_BUTTON -> {
                    finish()
                }
            }
        }
    }

    private fun initAdapter() {
        binding.rvRoot.adapter = mAdapter


        // 普通闪光
        headerBinding.tvCommon.setOnClickListener {
            UMPostUtils.onEvent(this, "call_normal_click")

            startActivity(
                Intent(
                    this,
                    EditCommonLightningActivity::class.java
                )
            )
        }

        // 摩斯电码闪光
        headerBinding.tvMorse.setOnClickListener {
            UMPostUtils.onEvent(this, "call_morse_click")

            startActivity(
                Intent(
                    this,
                    EditMorseActivity::class.java
                )
            )
        }
        mAdapter.addHeaderView(headerBinding.root)

        initFooter()
    }

    private fun initFooter() {
        initFooterData(footerBinding)
        mAdapter.addFooterView(footerBinding.root)
    }

    private fun initFooterData(footerBinding: FooterCallLightningBinding) {
        viewModel.presetListLiveData.value?.forEach { entity ->


            val footerView = LayoutInflater.from(this).inflate(
                R.layout.adapter_call_lightning,
                footerBinding.llFooterList,
                false
            )

            if (entity.isCheck) {
                footerView.findViewById<ConstraintLayout>(R.id.root_view)
                    .setBackgroundResource(R.mipmap.icon_select_bg)
            }

            val background = when (entity.title) {
                "love" -> {
                    R.mipmap.icon_love
                }

                "sos" -> {
                    R.mipmap.icon_sos
                }

                "心跳" -> {
                    R.mipmap.icon_heart
                }

                "爆闪" -> {
                    R.mipmap.icon_lightning
                }

                "敲门" -> {
                    R.mipmap.icon_knock_door
                }
                else -> R.drawable.shape_solid_474453_radius_6
            }

            footerView.findViewById<TextView>(R.id.tv_item).apply {
                setBackgroundResource(background)
                text = entity.title
            }

            footerView.findViewById<ImageView>(R.id.iv_icon_morse).visibility =
                if (entity.isMorse == true) View.VISIBLE else View.GONE

            // 预设闪光设置
            footerView.setOnClickListener {

                mAdapter.resetCheckStatus()

                viewModel.presetListLiveData.value?.forEach {
                    it.isCheck = false
                }
                entity.isCheck = true

                UMPostUtils.onEvent(this, "call_preset_click")

                Toast.makeText(this, "设置成功", Toast.LENGTH_SHORT).show()
                MMKV.defaultMMKV().encode(Constant.SAVE_CURRENT_LIGHTNING, entity)
                when (entity.title) {
                    "love" -> {
                        thread = null
                        thread?.stopThread()
                        thread = LightningThread(
                            this.applicationContext,
                            entity.lightNightList, 1
                        )
                        thread?.start()
                    }

                    "sos" -> {
                        thread = null
                        thread?.stopThread()
                        thread = LightningThread(
                            this.applicationContext,
                            entity.lightNightList, 1
                        )
                        thread?.start()
                    }

                    "心跳" -> {
                        thread = null
                        thread?.stopThread()
                        thread = LightningThread(
                            this.applicationContext,
                            entity.lightNightList, 2
                        )
                        thread?.start()
                    }

                    "爆闪" -> {
                        thread = null
                        thread?.stopThread()
                        thread = LightningThread(
                            this.applicationContext,
                            entity.lightNightList, 50
                        )
                        thread?.start()
                    }

                    "敲门" -> {
                        thread = null
                        thread?.stopThread()
                        thread = LightningThread(
                            this.applicationContext,
                            entity.lightNightList, 2
                        )
                        thread?.start()
                    }
                }

                MMKV.defaultMMKV()
                    .encode(
                        Constant.MMKV_SAVE_PRESET_CALL_LIGHTNING,
                        CallLightningCache(viewModel.presetListLiveData.value)
                    )
                footerBinding.llFooterList.removeAllViews()
                initFooterData(footerBinding)
            }

            footerBinding.llFooterList.addView(footerView)
        }
    }

    override fun onResume() {
        super.onResume()
        viewModel.getCommonList()
        mAdapter.setList(viewModel.commonListLiveData.value)
        setEditStatus()

    }

    private fun setEditStatus() {
        if (mAdapter.data.isNullOrEmpty()) {
            binding.viewTitleBar.rightTextView.isEnabled = false
            binding.viewTitleBar.rightTextView.setTextColor(Color.parseColor("#666666"))
        } else {
            binding.viewTitleBar.rightTextView.setTextColor(Color.parseColor("#ffffff"))
            binding.viewTitleBar.rightTextView.isEnabled = true
        }
    }

    override fun onDestroy() {
        thread?.stopThread()
        thread = null
        super.onDestroy()
    }
}